import asyncio
import websockets
import os
from pathlib import Path

# ---------------------- 硬编码配置 ----------------------
TARGET_IMAGE = "/data/control_communication/results/video/0.jpg"  # 直接修改这里指定图片路径
SEND_INTERVAL = 1  # 发送间隔（秒）
WS_PORT = 8765  # WebSocket 端口



async def push_single_image(websocket):
    """推送指定图片给客户端"""
    try:
        with open(TARGET_IMAGE, "rb") as f:
            image_data = f.read()

        # 持续发送（根据需求选择单次或循环发送）
        while True:
            await websocket.send(image_data)
            print(f"成功发送图片: {os.path.basename(TARGET_IMAGE)}")
            await asyncio.sleep(SEND_INTERVAL)

    except FileNotFoundError:
        print(f"图片文件已被移除: {TARGET_IMAGE}")
    except Exception as e:
        print(f"发送失败: {str(e)}")


# ---------------------- WebSocket 处理器 ----------------------
async def handle_connection(websocket, path):
    """处理客户端连接"""
    client_ip = websocket.remote_address[0]
    print(f"客户端连接: {client_ip}")

    try:
        await push_single_image(websocket)
    except websockets.exceptions.ConnectionClosed:
        print(f"客户端断开: {client_ip}")
    finally:
        await websocket.close()


# ---------------------- 服务启动 ----------------------
async def main():
    # 启动WebSocket服务器
    async with websockets.serve(handle_connection, "0.0.0.0", WS_PORT):
        print(f"图片推送服务已启动，监听端口: {WS_PORT}")
        print(f"正在推送指定图片: {TARGET_IMAGE}")
        await asyncio.Future()  # 永久运行


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("服务已关闭")